package com.bao123.gateway.filter;

import com.bao123.gateway.constant.NotNeedFilterConstant;
import com.bao123.jwt.exception.TokenErrorException;
import com.bao123.jwt.service.JwtService;
import com.google.common.net.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;

/**
 * jwt验证过滤器
 * @author lbw
 */
public class JwtCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<JwtCheckGatewayFilterFactory.Config> {
    @Autowired
    private JwtService jwtService;

    public JwtCheckGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            //判断是不是登录页面的请求
            String path = exchange.getRequest().getURI().getPath();
            System.out.println(path);
            if (NotNeedFilterConstant.checkPathIsNotFilter(path)){
                return chain.filter(exchange);
            }
            HttpCookie tokenCookie = exchange.getRequest().getCookies().getFirst("token");
            if (tokenCookie != null){
                String token = tokenCookie.getValue();
                try{
                    jwtService.verifyAndGetClaimsByToken(token);
                    return chain.filter(exchange);
                } catch (TokenErrorException e){
                    String url = "/userinfo/index.html";
                    ServerHttpResponse response = exchange.getResponse();
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    response.getHeaders().set(HttpHeaders.LOCATION, url);
                    return response.setComplete();
                }
            }
            String url = "/userinfo/index.html";
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.SEE_OTHER);
            response.getHeaders().set(HttpHeaders.LOCATION, url);
            return response.setComplete();
        };
    }

    public static class Config{
        //Put the configuration properties for your filter here
    }
}
